//
//  HNOrderProductDetailController.m
//  baidaifu
//
//  Created by 朱传正 on 2017/2/8.
//  Copyright © 2017年 haoniu. All rights reserved.
//

#import "HNOrderProductDetailController.h"
#import "AppDelegate.h"

@interface HNOrderProductDetailController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIScrollView *contentScrollView;

@property (nonatomic,strong) UILabel *topTitle;

@property (nonatomic,strong) UIButton *topBackBtn;

@property (nonatomic,retain) UIImagePickerController * imagePicker;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) NSString *imageStr;

@property (nonatomic,strong) NSLock *imageLock;

@end

@implementation HNOrderProductDetailController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //在其他离开改页面的方法同样加上下面代码
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTopView];
    self.title = @"商城";
    AppDelegate * app = [UIApplication sharedApplication].delegate;
    app.appCustomDelegate = self;
    _contentScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,64, kScreen_Width, kScreen_Height - 64)];
    
    [self.view addSubview:_contentScrollView];
    
    MJRefreshGifHeader *header = [[MJRefreshGifHeader alloc]init];
    
    [header setRefreshingBlock:^(void){
        [self reloadWebView];
    }];
    self.contentScrollView.mj_header = header;
    
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@?sessionId=%@&&goodsId=%@",url_web_ProductDetail,static_sessionId,_goodsId];
    
    NSLog(@"%@",_webViewUrl);
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0, _contentScrollView.frame.size.width, _contentScrollView.frame.size.height)];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.suppressesIncrementalRendering = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [_contentScrollView addSubview:_webView];
    
    
}

-(void)createTopView{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 64)];
    topView.backgroundColor = RGB(249, 249, 249);
    [self.view addSubview:topView];
    
    _topTitle = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width/2 - 60,20,120,44)];
    _topTitle.numberOfLines = 1;
    _topTitle.clipsToBounds = YES;
    _topTitle.layer.cornerRadius = 4;
    _topTitle.textAlignment = NSTextAlignmentCenter;
    _topTitle.font = [UIFont systemFontOfSize:15];
    _topTitle.textColor = RGBJ(44);
    _topTitle.text = @"商城";
    [topView addSubview:_topTitle];
    
    _topBackBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_topBackBtn setFont:[UIFont systemFontOfSize:15]];
    [_topBackBtn setBackgroundImage:[UIImage imageNamed:@"xiangyou.png"] forState:UIControlStateNormal];
    [_topBackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _topBackBtn.frame = CGRectMake(8,28,24,24);
    [_topBackBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_topBackBtn];
    
}

-(void)backAction{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
//                NSLog(@"回归主线程");
//                [self.view resignFirstResponder];
//                NSDictionary * userInfo = [[NSDictionary alloc]initWithObjectsAndKeys:@"NO",@"isHidden", nil];
//                
//                NSNotification * notice = [NSNotification notificationWithName:Notification_AGGTabViewController object:nil userInfo:userInfo];
//                [[NSNotificationCenter defaultCenter]postNotification:notice];
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });
        });
    }
    NSLog(@"-------goBack---------");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    
    
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
    
    
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"====webViewDidFinishLoad");
    
    NSString *title =  [_webView stringByEvaluatingJavaScriptFromString:@"getHtmlTitle();"];
    
    NSLog(@"----------%@",title);
    
    self.topTitle.text = title;
    
    
    //调用JS 的方法
    //    NSString *title = [_webView   stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"test"]];
    
    [self setFd_prefersNavigationBarHidden:YES];
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"] = self;
    
    //设置下webView ContentSize
    CGFloat  webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    
    NSLog(@"%f",webViewHeight);
    
    //    if (webViewHeight > _webView.frame.size.height) {
    //        CGRect frame = _webView.frame;
    //        frame.size.height = webViewHeight;
    //        _webView.frame = frame;
    //
    //    }else{
    webViewHeight = kScreen_Height;
    //    }
    
    //    _contentScrollView.contentSize = CGSizeMake(kScreen_Width,  webViewHeight);
}

- (void)setFd_prefersNavigationBarHidden:(BOOL)hidden
{
    objc_setAssociatedObject(self, @selector(fd_prefersNavigationBarHidden), @(hidden), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)fd_prefersNavigationBarHidden
{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlStr = [[request URL] absoluteString];
    
    NSLog(@"urlStr = %@",urlStr);
    //http://192.168.1.111:8080/index.html
    //    NSRange range = NSMakeRange(28, 5);
    //
    //    //用边界截取起始位置为第四个，长度为5个长度
    //
    //    NSString *aString = [urlStr substringWithRange:range];
    //    NSLog(@"%@",aString);
    if ([urlStr containsString:@"/index.html"]) {
        _contentScrollView.frame = CGRectMake(0,0, mainScreenSize.width, mainScreenSize.height);
        _webView.frame = CGRectMake(0,0, _contentScrollView.frame.size.width, _contentScrollView.frame.size.height);
        [_topBackBtn setHidden:YES];
        
    }else{
        _contentScrollView.frame = CGRectMake(0,64, mainScreenSize.width, mainScreenSize.height  - 64);
        _webView.frame = CGRectMake(0,0, _contentScrollView.frame.size.width, _contentScrollView.frame.size.height);
        [_topBackBtn setHidden:NO];
        
    }
    return YES;
    
    
}

-(void)reloadWebView{
    [self.webView reload];
    [_contentScrollView.mj_header endRefreshing];
}

#pragma mark - HNWebJSExport
-(void)HNWebJSExportBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
//                [self.view resignFirstResponder];
//                NSDictionary * userInfo = [[NSDictionary alloc]initWithObjectsAndKeys:@"NO",@"isHidden", nil];
//                
//                NSNotification * notice = [NSNotification notificationWithName:Notification_AGGTabViewController object:nil userInfo:userInfo];
//                [[NSNotificationCenter defaultCenter]postNotification:notice];
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });
        });
    }
    NSLog(@"-------goBack---------");
}



-(void)HNWebJSExportGotoLoginVC{
    [AppConfig removeUserInfo];
    
    [[EMClient sharedClient] logout:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - HNWebJSExportUpdateImageStr
-(void )HNWebJSExportUpdateImageStr{
    
    
    [self updateUserImage];
    
    
}

-(void)updateUserImage{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),^{
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", @"拍照", nil];
            actionSheet.delegate = self;
            actionSheet.tag = 1001;
            [actionSheet showInView:self.view];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            self.imagePicker.allowsEditing = YES;
        });
    });
}

#pragma mark - 判断设备是否有摄像头
- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==1001) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.editing = YES;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        if (buttonIndex == 0)
        {
            //相册
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //[self presentModalViewController:_imagePicker animated:YES];
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }else if (buttonIndex == 1){
            //照相机
            if ([self isCameraAvailable]) {
                _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //[self presentModalViewController:_imagePicker animated:YES];
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else{
                [self showHint:@"该设备没有摄像头"];
            }
        }else
        {
            //取消
        }
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.5];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    //[picker dismissModalViewControllerAnimated:YES];
    //保持状态栏颜色---为黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
-(void)saveImage:(UIImage *)image{
    NSLog(@"image = %@",image);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_update_userInfo_image parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片
        __block UIImage * changeImage = [self compressImage:image toTargetWidth:333];
        
        NSData *data = UIImagePNGRepresentation(changeImage);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"%@",data);
        
        
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        
        
        if ([result isEqualToString:@"1"]) {
            _imageStr = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_imageStr);
            
            [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadSuccess('%@');",_imageStr]];
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


#pragma mark - HNWebJSExportPay
-(void)HNWebJSExportPayGetOrserSnandPayValue:(NSString *)orderSn :(NSString *)payValue{
    
    
    NSLog(@"%@ %@",orderSn,payValue);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(),^{
            NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
            
            NSString *payType = nil;
            if ([payValue isEqualToString:@"0"]) {
                payType = @"alipay";
            }else{
                payType = @"weixinPay";
            }
            
            [param setObject:payType forKey:@"payType"];
            
            [param setObject:orderSn forKey:@"orderSn"];
            
            NSLog(@"param = %@",param);
            
            
            AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager POST:url_order_pay parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSError * error;
                NSLog(@"responseObject = %@",responseObject);
                
                NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                [self hideHud];
                if (error) {
                    NSLog(@"====error1:%@",error);
                    [self showHint:@"获取支付信息失败"];
                    NSLog(@"==dict:%@",data);
                    return;
                }
                NSLog(@"==dict:%@",data);
                
                NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
                if ([result isEqualToString:@"1"]) {
                    NSDictionary *backGoodsDic = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
                    NSLog(@"backGoodsDic = %@",backGoodsDic);
                    
                    
                    if ([payValue isEqualToString:@"0"]) {
                        NSString *sign_content = [NSString stringWithFormat:@"%@",[backGoodsDic objectForKey:@"sign_content"]];
                        [HNAllJSExport AliPayOrder:sign_content];
                        
                        
                    }else if([payValue isEqualToString:@"1"]){
                        [HNAllJSExport WeiXinPayOrder:backGoodsDic];
                        
                    }
                    
                    
                }else{
                    NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                    if ([info isEqualToString:msg_InvalidLoginInformation]) {
                        
                        [AppConfig removeUserInfo];
                        
                        [[EMClient sharedClient] logout:YES];
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                        
                        LoginViewController *loginVC = [[LoginViewController alloc]init];
                        
                        [self.navigationController pushViewController:loginVC animated:YES];
                    }
                    [self showHint:info];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
                NSLog(@"====error:%@",error);
                [self hideHud];
                [self showHint:@"获取支付信息失败"];
            }];
            
        });
    });
    
    
    
}

#pragma mark - 支付回调
-(void)PingPayCallBack:(BOOL)bol{
    
    if (bol) {
        
        [self showHint:@"支付成功"];
        if ([self.webView canGoBack]) {
            [self.webView goBack];
            
        }else{
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                dispatch_async(dispatch_get_main_queue(),^{
                    NSLog(@"回归主线程");
                    [self.view resignFirstResponder];
                    NSDictionary * userInfo = [[NSDictionary alloc]initWithObjectsAndKeys:@"NO",@"isHidden", nil];
                    
                    NSNotification * notice = [NSNotification notificationWithName:Notification_AGGTabViewController object:nil userInfo:userInfo];
                    [[NSNotificationCenter defaultCenter]postNotification:notice];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
            });
        }
        
    }else{
        [self showHint:@"支付失败"];
    }
}

-(void)HNWebJSExportUpdateHeight{
    
    JSContext *context=[_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"] = self;
    
    //设置下webView ContentSize
    CGFloat  webViewHeight = [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    
    NSLog(@"%f",webViewHeight);
    
    if (webViewHeight > _webView.frame.size.height) {
        CGRect frame = _webView.frame;
        frame.size.height = webViewHeight;
        _webView.frame = frame;
        
    }else{
        webViewHeight = kScreen_Height;
    }
    
    _contentScrollView.contentSize = CGSizeMake(kScreen_Width,  webViewHeight);
}


#pragma mark - HNCustomerServiceJSExport 客服咨询
-(void)HNCustomerServiceJSExportChat:(NSString *)sellerTel{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(),^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:sellerTel]];
        });
    });
    
}


@end
